package cn.gistone.visualeditor.business.service.impl;

import cn.gistone.visualeditor.business.mapper.PictureRepository;
import cn.gistone.visualeditor.business.service.IPictureService;
import cn.gistone.visualeditor.dto.PicQueryDto;
import cn.gistone.visualeditor.entity.Picture;
import cn.gistone.visualeditor.utils.PageResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PictureServiceImpl implements IPictureService {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private PictureRepository pictureRepository;


    /**
     * 分页高级查询
     * @param dto
     * @return
     */
    @Override
    public PageResult<Picture> queryPage(PicQueryDto dto) {
        Query query = new Query(Criteria.where("type").is(dto.getType()));
        if(StringUtils.isNotBlank(dto.getImageName())){
            //模糊匹配
            String pattern = ".*?" + dto.getImageName() + ".*?";
            query.addCriteria(Criteria.where("imageName").regex(pattern));
        }
        //查询总条数
        Long count = mongoTemplate.count(query, Picture.class);
//        //设置排序
//        query.with(Sort.by(new Sort.Order(Sort.Direction.DESC, "updateTime")));
        //设置分页
        Pageable pageable = PageRequest.of(dto.getCurrent(),dto.getSize());
        query.with(pageable);
        List<Picture> list = mongoTemplate.find(query,Picture.class);
        return new PageResult<>(count,list);
    }

    /**
     * 根据id删除
     * @param id
     */
    @Override
    public void deleteById(String id) {
        pictureRepository.deleteById(id);
    }
}
